<template>
  <div class="page-container">
    <div class="space-x-2">
      <a-button type="primary" @click="handleImport">
        <template #icon><ImportOutlined /></template>导入
      </a-button>
    </div>
    <a-button class="w-full my-4" type="dashed" @click="handleModalAdd">
      <template #icon><PlusOutlined /></template>添加
    </a-button>
    <ModalCollapse
      v-for="(item, index) in filterList"
      v-model:checked="item.checked"
      :closable="false"
      :key="state.modalList.length - ((state.pageVo.currentPage - 1) * state.pageVo.pageSize + index)"
      :index="state.modalList.length - ((state.pageVo.currentPage - 1) * state.pageVo.pageSize + index)"
      @close="handelModalClose(state.modalList.length - ((state.pageVo.currentPage - 1) * state.pageVo.pageSize + index))"
    >
      <ModalForm v-model:data="item.data" :type="item.type" :upDate="state.upDate" :part-no-list="state.partNoList" @setPartNoList="(data) => setPartNoList(index, data)" ref="modalFormRef" />
    </ModalCollapse>
    <div class="flex justify-end" v-if="state.modalList && state.modalList.length > 1">
      <a-pagination
        v-model:current="state.pageVo.currentPage"
        v-model:pageSize="state.pageVo.pageSize"
        :pageSizeOptions="state.pageVo.pageSizeOptions"
        show-quick-jumper
        show-size-changer
        :total="state.modalList.length"
        :show-total="(total) => `共 ${total} 条`"
        @change="onPageChange"
      />
    </div>
    <div class="space-x-2 w-full text-center my-4">
      <a-button @click="cancel">取消</a-button>
      <a-button type="primary" @click="submit">提交</a-button>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { createVNode, onMounted, reactive, ref, getCurrentInstance, computed } from 'vue';
import ModalForm from './components/modalForm.vue';
import ModalCollapse from '@/views/archivesManage/addArchivesFile/components/modalCollapse.vue';
import { fileListInput, fileListSelect } from '@/config/api/archivesFile';
import { useRouter } from 'vue-router';
import { message, Modal } from 'ant-design-vue';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { DYNAMICLAYERUPLOAD } from '@/mixins/subject/subject-types';
import { Api } from '@/config/api/archivesFile';
import { throttle } from 'xe-utils';

const { proxy }: any = getCurrentInstance();
const state = reactive({
  modalList: [],
  pageVo: {
    pageSize: 10,
    currentPage: 1,
    pageSizeOptions: ['10', '25', '50', '100']
  },
  partNoList: [],
  upDate: 1 // 再次点击导入更新数据
});
const modalFormRef = ref(null);
const router = useRouter();
const filterList = computed(() => {
  const current = state.pageVo.currentPage;
  const size = state.pageVo.pageSize;
  return state.modalList.slice((current - 1) * size, current * size);
});

onMounted(() => {
  if (!history.state?.params?.ids) throw new Error('缺少参数');
  const params = { list: history.state.params.ids };
  fileListSelect(params).then((result) => {
    if (result.success) {
      const fileList = result.data;
      for (let i = 0; i < fileList.length; i++) {
        state.modalList.push({
          type: 'EDIT',
          checked: true,
          data: fileList[i]
        });
      }
    }
  });
});
// 导入文件信息
function handleImport() {
  proxy.$NotificationPubSub.pushParams({
    key: DYNAMICLAYERUPLOAD,
    value: {
      state: {
        url: Api.findListImportFile,
        downloadUrl: Api.fileGetImportTemplate,
        downloadProtType: 'post',
        downloadParams: { templateCode: 'archives_input' },
        downloadHeader: true,
        downloadName: '下载导入模板',
        downloadRule: '仅允许上传excel格式；文件大小不超过10M',
        multiple: true,
        maxCount: 10,
        hideMessage: true,
        callback: (data) => {
          parseImportData(data);
        }
      }
    }
  });
}
// 解析文件信息
function parseImportData(data) {
  data.errorMessage ? message.warning({ content: data.errorMessage, duration: 6 }) : message.success('上传成功！');
  if (data.list && data.list.length > 0) {
    state.upDate++;
    const codeList = state.modalList.map((item) => item.data.filesBoxCode);
    for (let i = 0; i < data.list.length; i++) {
      // 根据档案编码，已存在的数据覆盖，无则添加
      if (codeList.includes(data.list[i].filesBoxCode)) {
        Object.assign(state.modalList[state.modalList.findIndex((obj) => obj.data.filesBoxCode == data.list[i].filesBoxCode)], { type: 'IMPORT', data: data.list[i], upDate: state.upDate });
      } else {
        state.modalList.splice(codeList.indexOf(data.list[i].filesBoxCode), 0, {
          type: 'IMPORT',
          checked: true,
          data: data.list[i],
          upDate: state.upDate
        });
      }
    }
  }
}
// 归档文件窗口添加
function handleModalAdd() {
  state.modalList.unshift({
    type: 'ADD',
    checked: true,
    data: {}
  });
  // 返回第一页
  if (state.modalList.length > state.pageVo.pageSize) state.pageVo.currentPage = 1;
}
// 归档文件窗口关闭
function handelModalClose(index) {
  Modal.confirm({
    title: '是否确认删除？',
    icon: createVNode(ExclamationCircleOutlined),
    okText: '确定',
    cancelText: '取消',
    onOk() {
      state.modalList.splice(state.modalList.length - index, 1);
      // 删除最后一条时页数减一
      if (filterList.value.length == 0 && state.pageVo.currentPage !== 1) {
        state.pageVo.currentPage -= 1;
      }
    },
    onCancel() {}
  });
}
// 分页
function onPageChange(pageNumber, pageSize) {
  state.pageVo.currentPage = pageNumber;
  state.pageVo.pageSize = pageSize;
}
function cancel() {
  router.go(-1);
}
// 提交
const submit = throttle(async function () {
  let isError;
  for (let i = 0; i < modalFormRef.value.length; i++) {
    // 校验已选项
    if (state.modalList[i].checked) {
      await modalFormRef.value[i].isValidateFields().catch((error) => {
        console.warn(error);
        isError = true;
      });
    }
  }
  const fileList = state.modalList.filter((item) => item.checked).map((item) => item.data);
  const params = {
    list: fileList
  };
  if (isError) return;
  fileListInput(params).then((result) => {
    if (result.success) {
      message.success('提交成功');
      router.go(-1);
    }
  });
}, 3000);
// 件号输入
function setPartNoList(index, data) {
  state.partNoList[index] = data;
}
</script>

<style lang="less" scoped></style>
